#include "PageRelevancy.h"
#include "UIInterface.h"
#include "PageElement.h"
#include <QEvent>
#include <QKeyEvent>

#include "MyEvent.h"

PageRelevancy::PageRelevancy()
{
}

PageRelevancy* PageRelevancy::getInstance()
{
	static PageRelevancy ins;
	return &ins;
}

void PageRelevancy::setFocus(QWidget* widget)
{
	m_focusWidget = widget;
}

QWidget* PageRelevancy::focus()
{
	return m_focusWidget;
}

void PageRelevancy::insertRelevancy(QWidget* first, QWidget* second)
{
	m_relevancyMap.insert(first, second);
}

QWidget* PageRelevancy::getRelevancyByParent(QWidget* parent)
{
	if (m_relevancyMap.contains(parent))
	{
		return  m_relevancyMap[parent];
	}
	return nullptr;

}

QWidget* PageRelevancy::getRelevancyByChild(QWidget* child)
{
	for (auto  key : m_relevancyMap.keys())
	{
		if (m_relevancyMap[key] == child)
		{
			return key;
		}
	}
	return nullptr;
}

void PageRelevancy::insertParent(QWidget* parent, QWidget* child)
{
	m_parentMap.insert(parent, child);
}

QWidget* PageRelevancy::getParent(QWidget* child)
{
	for (auto key : m_parentMap.keys())
	{
		if (m_parentMap[key] == child)
		{
			return key;
		}
	}
	return nullptr;
}

QWidget* PageRelevancy::getChild(QWidget* parent)
{
	if (m_parentMap.contains(parent))
	{
		return m_parentMap[parent];
	}
	return nullptr;
}

bool PageRelevancy::event(QEvent* event)
{
	if (auto page = dynamic_cast<PageElement *>(m_focusWidget))
	{

		if (event->type() == MyEventType)
		{
			MyEvent* myEvent = static_cast<MyEvent*>(event);
			switch (myEvent->getKeyValue())
			{
			case myEvent::up:
				page->up();
				break;
			case myEvent::down:
				page->down();
				break;
			case myEvent::left:
				page->left();
				break;
			case myEvent::right:
				page->right();
				break;
			case myEvent::esc:
				page->esc();
				break;
			case myEvent::enter:
				page->enter();
				break;
			default:
				return false;
			}

			return true;
		}
	}
}
